<template>
  <div class="user-management">
    <div class="search-container">
      <div class="search-input">
        <el-input
          placeholder="请输入内容"
          prefix-icon="el-icon-search"
          v-model="paramsForm.keywords"
          style="margin-left: 40px;">
        </el-input>
      </div>
      <el-button type="primary" size="small" @click="getUserList()" class="search-button">搜索按钮</el-button>
      <el-button type="primary" size="small" @click="resetDialog()" class="search-button">重置按钮</el-button>
    </div>
      <div class="button-container">
          <el-button type="primary" @click="showAddDialog">新增用户</el-button>
          <el-button type="danger" @click="deleteSelected" :disabled="selectedRows.length === 0">删除所选</el-button>
      </div>

    <el-table :data="users" style="width: 100%; border-radius: 10px;" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="id" label="ID"></el-table-column>
      <el-table-column prop="avatar" label="头像">
        <template slot-scope="scope">
          <img :src="scope.row.avatar" alt="头像" style="width: 50px; height: 50px;">
        </template>
      </el-table-column>
      <el-table-column prop="username" label="用户名"></el-table-column>
      <el-table-column prop="nickname" label="昵称"></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column prop="createTime" label="创建时间"></el-table-column>
      <el-table-column prop="sign" label="签名"></el-table-column>
      <el-table-column prop="sex" label="性别"></el-table-column>
      <el-table-column prop="roleName" label="用户角色"></el-table-column>
      <el-table-column label="操作" style="min-width:200px;">
          <template slot-scope="scope">
              <el-row type="flex" justify="space-between" class="action-buttons">
              <el-col style="margin-right: 5px;">
                  <el-button type="primary" size="mini" @click="showEditDialog(scope.row)">编辑</el-button>
              </el-col>
              <!-- <el-col>
                  <el-button type="danger" size="mini" @click="editRole(scope.row)">分配角色</el-button>
              </el-col> -->
              </el-row>
          </template>
      </el-table-column>
    </el-table>

    <div style="width: 40px; margin-top: 8px">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="paramsForm.pageNum"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="paramsForm.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <el-dialog :visible.sync="dialogVisible" title="用户信息" @close="resetDialog">
      <el-form :model="dialogForm" :rules="rules" ref="dialogForm" label-width="180px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="dialogForm.username" :disabled="isEdit" required></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname" required>
          <el-input v-model="dialogForm.nickname"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex" required>
          <el-switch
            v-model="dialogForm.sex"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-text="男"
            inactive-text="女"
            :active-value= "1"
            :inactive-value= "0"
          >
          </el-switch>
        </el-form-item>
        <el-form-item label="签名" prop="sign">
          <el-input v-model="dialogForm.sign"></el-input>
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <el-upload class="image-uploader" action="/api/upload/image" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="dialogForm.avatar" :src="dialogForm.avatar
            " class="image">
            <i v-else class="el-icon-plus image-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="邮箱" prop="email" required>
          <el-input v-model="dialogForm.email"></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="captcha">
          <el-input v-model="dialogForm.captcha"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" required>
          <el-input v-model="dialogForm.password" :disabled="isEdit"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetDialog">取消</el-button>
        <el-button type="primary" @click="submit">保存</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { getUserInfoList,postUserInfo,putUserInfoUpdate,deleteUserInfoById } from '@/api/controller';
import request from '@/utils/request';
export default {
  mounted() {
    this.getUserList();
  },
  data() {
    let users
    return {
      selectedImage: null,
      imageUrl: '',
      total:0,
      paramsForm: {
        pageSize: 10,
        pageNum: 1,
        keywords: "",
        status:1,
      },
      users,
      selectedRows: [],
      dialogVisible: false,
      dialogForm: {
        username: '',
        nickname: '',
        sex: '',
        sign: '',
        avatar: '',
        email: '',
        captcha: '',
        // roleName:'',
        // status:'',
        password:''
      },
      rules: {
          username: [
            { required: true, message: "用户名不能为空", trigger: "blur" },
          ],
          email: [
            { required: true, message: "用户邮箱不能为空", trigger: "blur" },
          ],
          password: [
            { required: true, message: "密码不能为空", trigger: "blur" },
          ],
          nickname: [
            { required: true, message: "用户邮箱不能为空", trigger: "blur" },
          ],
          sex: [
            { required: true, message: "性别", trigger: "blur" },
          ],
        },
      isEdit: false,
      input1:'',
      
    };
  },
  methods: {
    showAddDialog() {
      this.isEdit = false;
      this.dialogVisible = true;
    },
    showEditDialog(row) {
      this.isEdit = true;
      console.log("click edit")
      Object.assign(this.dialogForm, row);
      this.dialogVisible = true;
    },
    resetDialog() {
      this.dialogFormusername = '',
      this.dialogFormnickname = '',
      this.dialogFormsex = '',
      this.dialogFormsign = '',
      this.dialogFormavatar = '',
      this.dialogFormemail = '',
      this.dialogFormcaptcha = '',
      this.dialogFormpassword = '',
      this.paramsForm.keywords = '',
      this.dialogVisible = false;
      this.getUserList();
    },
    submit() {
      this.$refs.dialogForm.validate(valid => {
        if (valid) {
          if (this.isEdit) {
            this.editUser();
            this.getUserList();
          } else {
            this.addUser();
            this.getUserList();
          }
        } else {
          console.log("表单验证不通过");
        }
      });
    },
    deleteUser(row) {
      console.log("id", row.id);
      let id = parseInt(row.id);
      deleteUserInfoById(id)
        .then((response) => {
          console.log(response);
        })
        .catch((error) => {
          this.$message.error(error.message);
        });
    },
    handleSelectionChange(selection) {
      this.selectedRows = selection;
    },
    deleteSelected() {
      this.$confirm('确定要删除吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
      }).then(() => {
        // 执行删除操作
        this.selectedRows.forEach(row => {
            this.deleteUser(row);
        });
        this.selectedRows = [];
      }).catch(() => {
        // 取消删除操作
        console.log('取消删除');
      });
      this.getUserList();
    },
    editRole(row){
      console.log(row.id);
    },
    handleAvatarSuccess(res) {
      this.dialogForm.avatar = res.data.imageUrl
    },
    // handleAvatarSuccess1(res) {
    //   this.addUserForm.avatar = res.data.imageUrl
    // },
    beforeAvatarUpload(file) {
      let types = ['image/jpeg', 'image/jpg', 'image/png'];
      const isJPG = types.includes(file.type);
      const isLt2M = file.size / 1024 / 1024 < 20

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG、JPEG、PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 20MB!');
      }
      return isJPG && isLt2M;
    },
    handleUploadImage(_event, insertImage, files) {
      for (let i in files) {
        const formData = new FormData()
        formData.append('file', files[i])
        request.post(`/upload/image`, formData).then(
          (response) => {
            const { data } = response
            insertImage({
              url: data.imageUrl,
              desc: 'desc',
            })
          },
          (error) => {
            this.$message.error(error.message)
          },
        )
      }
    },
    getUserList(){
      console.log("搜索关键词",this.paramsForm.keywords)
      getUserInfoList(this.paramsForm)
      .then((response) => {
        console.log(response);
        const {data} = response;
        console.log("data",data);
        this.users = data.list;
        this.total = data.total;
        console.log("users",this.users);
      })
      .catch((error) => {
        this.$message.error(error.message);
      });
    },
    addUser(){
      postUserInfo(this.dialogForm)
      .then((response) => {
        console.log(response);
        this.$message.success(response.message);
      })
      .catch((error) => {
        this.$message.error(error.message);
      });
    },
    editUser(){
      putUserInfoUpdate(this.dialogForm)
      .then((response) => {
        console.log(response);
        this.$message.success(response.message);
      })
      .catch((error) => {
        this.$message.error(error.message);
      });
    },
    handleSizeChange(val) {
      this.paramsForm.pageSize = val;
      this.getUserList();
    },
    handleCurrentChange(val) {
      this.paramsForm.pageNum = val;
      this.getUserList();
    },
  }
};
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.button-container {
  display: flex;
  justify-content: space-between;
  max-width: 250px;
  margin-bottom: 30px;
}

.action-buttons {
  min-width: 10px;
}

.el-message-box__btns {
  display: flex;
  padding: 5px 15px 0;
  text-align: right;
}

.search-container{
  display: flex;
  margin-bottom: 30px;
}

.search-input{
  width: 400px;
  margin-left: 300px;
}

.search-button{
  margin-left: 40px;
}
</style>